import Vue from 'vue';
import _ from "underscore";
import '../../static/z39pc/js/jquery-2.1.0.js';


export const mixinEditor = {
  data() {
    return {
      testEditor: null
    }
  },
  methods: {
    resizeEditor: function() {
      console.log("resize");
      var w = $("#taskeditor").width() -300;
      console.log(w)
      $("#taskeditor").resize( w+ 'px');
      $(".editormd-toolbar").resize('100%');
      $(".CodeMirror-wrap").css({'width': '50%', 'margin-top': '80px'});
      $(".editormd-preview").css({'width': '50%', 'top': '80px'});
    },
    showPreview: function() {
        try {
            //testEditor.previewing();
            $(".markdown-body").appendTo($(".editormd-preview"));
            //$("#layout").hide();
            //$("#layout").remove();
        } catch (e) {
            setTimeout(function() {
                showPreview();
            }, 5);
        };
    },
    addMask: function() {
      let _this = this
      var $document = $(document);
      var h = $document.height() + 'px';
      var w = $document.width() + 'px';
      var size = 'height:' + h + ';width:' + w + ';';
      var maskHtml = '<div id="editormd-mask" style="' + size + 'position:absolute;z-index:999;background-color:rgba(0,0,0,0.7);"></div>';
      $("body").append(maskHtml);
      $("#editormd-mask").click(function(){
        console.log(_this)
        for(let i = 0;i < _this.$children.length;i++){
          if(_this.$children[i].changeSwitch){
            _this.$children[i].changeSwitch()
            $('.task-detail-container').focus()
            return;
          }
        }
        $(this).remove();
      });
    },
    removeMask: function() {
      $("#editormd-mask").remove();
    },
    initEditor: function(){
      var that = this;
      if (typeof editormd === 'undefined') {
        var m = document.createElement('script');
        m.src = "/static/jslib/editormd.js";
        document.body.appendChild(m);
        m.onload = function() {
          that.createEditor();
        };
      } else {
        this.createEditor();
      }
    },
    createEditor: function() {
      var md = "";
      var that = this;
      var uploadUrl = "http://7dtime.tunnel.echomod.cn/apix/z39base/upload";
      that.testEditor = editormd("taskeditor", {
          width: '100%',
          height: '900',
          path: '/static/lib/',
          previewTheme: "dark",
          editorTheme: "pastel-on-dark",
          markdown: md,
          codeFold: true,
          //syncScrolling : false,
          saveHTMLToTextarea: true, // 保存 HTML 到 Textarea
          searchReplace: true,
          //watch : false,                // 关闭实时预览
          htmlDecode: "style,script,iframe|on*",
          emoji: true,
          taskList: true,
          tocm: true, // Using [TOCM]
          tex: true, // 开启科学公式TeX语言支持，默认关闭
          flowChart: true, // 开启流程图支持，默认关闭
          sequenceDiagram: true, // 开启时序/序列图支持，默认关闭,
          imageUpload: true,
          imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp", "mp4"],
          imageUploadURL: uploadUrl,
          crossDomainUpload: true,
          onlyTask: true,
          uploadCallbackURL: 'eval',
          mind: true,
          onload: function() {
              console.log('onload', this);
              var codeEditor = $(".CodeMirror-wrap")[0];
              //console.log("codeEditor:", codeEditor);
              codeEditor.ondragenter = function(e) {
                e.preventDefault();
                e.stopPropagation();
                console.log("dragenter");
                return false;
              };
              codeEditor.ondragover = function(e) {
                e.preventDefault();
                e.stopPropagation();
                console.log("dragiver");
                return false;
              };
              codeEditor.ondrop = function(e) {
                e.preventDefault();
                e.stopPropagation();
                console.log("drop");
                var files = e.dataTransfer.files
                console.log(files);
                
                that.ajaxUploader(uploadUrl, files, function(json){that.uploadCallback(json);});
                //that.uploadCallback({url: 'http://cdn.7dtime.com/time_tlog/2018-07-02_5tlxlgjgjck.jpg'});

                return false;
              };
          },
          toolbarIconsClass : {
              saveBlog: "fa-save"  // 指定一个FontAawsome的图标类
          },
          lang : {
              toolbar : {
                  saveBlog: "保存任务",
              }
          },
          // 自定义工具栏按钮的事件处理
          toolbarHandlers : {
              /**
               * @param {Object}      cm         CodeMirror对象
               * @param {Object}      icon       图标按钮jQuery元素对象
               * @param {Object}      cursor     CodeMirror的光标对象，可获取光标所在行和位置
               * @param {String}      selection  编辑器选中的文本
               */
              saveBlog : function(cm, icon, cursor, selection) {
                return;
                var md = that.testEditor.getMarkdown();
                var $taskDetail = $("#task-detail");
                var taskId = 0;
                if ($taskDetail.length > 0) {
                    var taskJson = JSON.parse($taskDetail.attr('data-task'));
                    taskId = taskJson.id || 0;
                }
                var taskDesc = md;

                api.taskSet({
                  id: taskId,
                  desc: taskDesc
                }).then(function(data){
                  if (typeof data == 'string') {
                    data = JSON.parse(data);
                  }
                  if (data.errno == 0) {
                    that.$message("保存成功");
                  } else {
                    that.$message("保存失败:" + data.errmsg);
                  }
                });
              }
          }
      });
      that.showPreview();
    },
    openTaskEditor: function(taskId, taskDesc) {
      $("#taskeditor").css({'right':340,'top':'-6%','left':'-3%'});
      $("#taskeditor").css({'z-index': 1100}).show();
      //console.log(taskDetail);
      //var md = taskDetail.desc || ""; //getDayMD([{name:"",desc:"",tasks: [taskDetail]}], false);
      this.testEditor.setMarkdown(taskDesc);
      this.resizeEditor();
      window.editor = this.testEditor;
      this.addMask();
    },
    closeTaskEditor: function() {
      $("#taskeditor").css({'z-index': 0}).hide();
      this.removeMask();
    },
    getEditorContent: function() {
      return this.testEditor.getMarkdown();
    },
    ajaxUploader: function(uploadUrl, files, callback) {
        console.log("my ajax upload begin");
        var that = this;
        var formdata = new FormData();
        formdata.append('file', files[0])

        var $taskDetail = $("#task-detail");
        if ($taskDetail.length > 0) {
            var taskJson = JSON.parse($taskDetail.attr('data-task'));
            formdata.append("taskid", taskJson.id || 0);
            formdata.append("uid", taskJson.uid || 0);
        }
        formdata.append('token', localStorage.getItem('token') || '');
        var loading = that.$loading({
          lock: false,
          text: '上传中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)',
          target: '.CodeMirror-wrap',
        });
        $(".el-loading-mask").css({'background-color': 'rgba(0,0,0,0.7)'});

        $.ajax({
          type: 'POST',
          url: uploadUrl,
          data: formdata,
          dataType: 'json',
          contentType: false,
          processData: false
        }).then(function(json) {
          loading.close();
          console.log("result:", json);
          //json.errno = 0;
          //json.data = 'http://cdn.7dtime.com/time_tlog/2018-07-02_5tlxlgjgjck.jpg';
          //json.data = 'https://www.zhangjikai.com/resource/demo.mp4';
          /**if (json.errno == 0) {
              dialog.find("[data-url]").val(json.data);
          } else {
              alert(json.errmsg);
          }**/
          callback(json);
        }, function (err) {
          loading.close();
          console.log(err);
        });

        return false;
    },
    uploadCallback: function(json) {
      var url = json.data;
      var link = url;
      if (!url) return false;

      var alt = "";
      var cm = this.testEditor;
      var cursor = cm.getCursor();
      var dotPos = url.lastIndexOf('.');
      var isVideo = false;
      if (dotPos >= 0) {
          var suffix = url.substring(dotPos+1);
          if (suffix == 'mp4') {
              isVideo = true;
          }
      }
      if (isVideo) {
          var videoHtml = '<video class="video-js" controls preload="auto" width="100%" poster="" data-setup=\'{"aspectRatio":"16:9"}\'>\
<source src="' + url + '" type=\'video/mp4\' >\
<p class="vjs-no-js">\
To view this video please enable JavaScript\
</p>\
</video>';
          videoHtml = "```video\n" + videoHtml + "\n```\n";
          cm.replaceSelection(videoHtml);
          cm.setCursor(cursor.line, cursor.ch + 2);
      } else {
          var altAttr = (alt !== "") ? " \"" + alt + "\"" : "";
          if (link === "" || link === "http://")
          {
              cm.replaceSelection("![" + alt + "](" + url + altAttr + ")");
          }
          else
          {
              cm.replaceSelection("[![" + alt + "](" + url + altAttr + ")](" + link + altAttr + ")");
          }

          if (alt === "") {
              cm.setCursor(cursor.line, cursor.ch + 2);
          }
      }
    }
  },
  mounted() {
    this.initEditor();
  }
};
